package com.lianyi.push.share.udpservice;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;

import com.lianyi.push.share.ConstantValue;
import com.lianyi.push.share.listener.UdpClientToSeiviceMessageListener;
import com.lianyi.push.util.CommonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


/**
 * ================================================
 * 作者: leilei
 * 版本: 1.0
 * 创建日期: 2018/4/8 20:18
 * 描述:
 * 修订历史:
 * ================================================
 */
@ChannelHandler.Sharable
public class UdpServerHandler
        extends SimpleChannelInboundHandler<DatagramPacket> {
    private Context mContext;
    private UdpClientToSeiviceMessageListener udpClientToSeiviceMessageListener;

    public UdpServerHandler(Context mContext, UdpClientToSeiviceMessageListener listener) {
        this.mContext = mContext;
        this.udpClientToSeiviceMessageListener = listener;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("UDP通道已经连接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }


//    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
//    @Override
//    protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
////        System.out.println("消息来源" + datagramPacket.sender().getHostString() + ":" + datagramPacket.sender().getPort());
//        // TODO Auto-generated method stub
//        // 因为Netty对UDP进行了封装，所以接收到的是DatagramPacket对象。
//        String body = datagramPacket.content().toString(CharsetUtil.UTF_8);
////        Log.e("收到客户端消息:", "收到客户端消息:" + body + "消息来源ip:" + datagramPacket.sender().getHostString() + ":" + datagramPacket.sender().getPort());
//        String ip = datagramPacket.sender().getHostString();
//        if (!TextUtils.isEmpty(ip) && !ip.equals(CommonUtils.getLocalIpAddress())) {
//            onReceiveData(ctx, datagramPacket, body);
//        }
//    }

//    private void onReceiveData(ChannelHandlerContext ctx, DatagramPacket datagramPacket, String date) {
//        if (!TextUtils.isEmpty(date)) {
//            if (ConstantValue.UDP_MESSAGE_UP_DATE.equals(date)) {
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject();
//                    jsonObject.put(ConstantValue.UDP_MESSAGE_TAG, ConstantValue.UDP_MESSAGE_GET_IP);
////                    jsonObject.put(ConstantValue.UDP_MESSAGE_DOCTOR, DoctorUtils.getInstance(mContext).getname());
//                    jsonObject.put(ConstantValue.UDP_MESSAGE_GET_IP, CommonUtils.getLocalIpAddress());
////                    jsonObject.put(ConstantValue.UDP_MESSAGE_HOSPITAL_NAME, PreferenceUtils.getInstance(mContext).getHospitalname());
//                    SharedPreferences spit = mContext.getSharedPreferences("toggle", Activity.MODE_PRIVATE); // 开关
//                    if (spit.getString("switch", "").equals("开")) {
//                        jsonObject.put(ConstantValue.UDP_MESSAGE_IS_MAIN, true);
//                    } else {
//                        jsonObject.put(ConstantValue.UDP_MESSAGE_IS_MAIN, false);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8), datagramPacket.sender());
//                ctx.writeAndFlush(data);
//            }
//        }
//    }

    /**
     * 客户端发送给服务器的消息
     *
     * @param ctx
     * @param datagramPacket
     * @throws Exception
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
        //        System.out.println("消息来源" + datagramPacket.sender().getHostString() + ":" + datagramPacket.sender().getPort());
        // TODO Auto-generated method stub
        // 因为Netty对UDP进行了封装，所以接收到的是DatagramPacket对象。
        String body = datagramPacket.content().toString(CharsetUtil.UTF_8);
//        Log.e("收到客户端消息:", "收到客户端消息:" + body + "消息来源ip:" + datagramPacket.sender().getHostString() + ":" + datagramPacket.sender().getPort());
        String ip = datagramPacket.sender().getHostString();
        if (!TextUtils.isEmpty(ip) && !ip.equals(CommonUtils.getLocalIpAddress())) {
//            onReceiveData(ctx, datagramPacket, body);
        }
        udpClientToSeiviceMessageListener.clientToServiceListener(ctx, datagramPacket);
    }
}
